import {
  CART_LIST,
  CHECK_ALL,
  UN_CHECK_ALL,
  CHECK_ITEM
} from './mutations-type'
import {
  Toast,
  Dialog
} from 'vant';
import axios from '@/http/index'
export default {
  state: {
    list: [],
    selectList: []
  },
  getters: {
    //判断是否全选
    isCheckedAll(state) {
      return state.list.length == state.selectList.length
    },
    //总价,总数量
    total(state) {
      let total = {
        num: 0,
        price: 0
      }
      state.list.forEach(v => {
        if (v.checked) {
          total.num += v.goods_num
          total.price += v.goods_price * v.goods_num
        }
      })
      return total
    }
  },
  mutations: {
    //初始化购物车数据
    [CART_LIST](state, cartArr) {
      if(!cartArr){
        state.list= []
        state.selectCart = []
        return
      }
      state.list = cartArr
      let selectCart = []
      cartArr.forEach(v => {
        selectCart.push(v.goods_id)
      })
      state.selectList = selectCart
    },
    //全选
    [CHECK_ALL](state) {
      state.selectList = state.list.map(v => {
        v.checked = true
        return v.id
      })
    },
    //全不选
    [UN_CHECK_ALL](state) {
      state.list.forEach(v => {
        v.checked = false
      })
      state.selectList = []
    },
    //单选
    [CHECK_ITEM](state, id) {
      let i = state.selectList.indexOf(id)
      if (i != -1) {
        state.selectList.splice(i, 1)
      } else {
        state.selectList.push(id)
      }
    }
  },
  actions: {
    //全选/全不选
    checkAllFn({
      getters,
      commit
    }) {
      getters.isCheckedAll ? commit('UN_CHECK_ALL') : commit('CHECK_ALL')
    },
    //购物车删除
    delGoodsFn({
      state,commit
    }, id) {
      if (!state.selectList.length && typeof (id) != 'string') return Toast('请选择商品')
      Dialog.confirm({
          message: '确定要删除这些商品吗',
        })
        .then(() => {
          if (typeof (id) == 'string') {
            id = [id]
            let newData = state.list.filter(v=>{
                return v.goods_id != id
            })
            state.list = newData
            state.selectList.splice(id,1)
          } else {
            //多个删除
            let newData = state.list.filter(v=>{
                return state.selectList.indexOf(v.goods_id) === -1
            })
            state.list = newData
            id = state.selectList
            state.selectList = []
          }
            axios({
              url: '/api/deleteCart',
              method: 'post',
              data: {
                goodsId: id
              },
              headers: {
                token: true
              }
            }).then(res => {
              if (res.data.success) {
                Toast(res.data.msg)
              }
            })
        }).catch(() => {
          // on cancel
        })
    }
  }
}
